package com.room.search.service.baidu;

import com.room.search.config.ApplicationProperties;
import com.room.search.response.RoomResult;
import com.room.search.service.dto.baidu.BaiduApiResponse;
import com.room.search.service.dto.baidu.BaiduAroundResultDTO;
import com.room.search.service.dto.baidu.BaiduQueryAroundDTO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.HttpMethod;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.List;

/**
 * By   : ghd.bright
 * Time : 2022/3/10
 * Description: 百度地图APi
 */

@Service
public class BaiduMapService {

    private static final Logger log = LoggerFactory.getLogger(BaiduMapService.class);

    private static final String OUT_PUT = "json";

    private final ApplicationProperties properties;
    private final RestTemplate restTemplate;

    public BaiduMapService(ApplicationProperties properties, RestTemplate restTemplate) {
        this.properties = properties;
        this.restTemplate = restTemplate;
    }

    public <T> BaiduApiResponse<T> doRequest(
        String url,
        ParameterizedTypeReference<BaiduApiResponse<T>> typeReference
    ) {

        return restTemplate.exchange(url, HttpMethod.GET, null, typeReference).getBody();
    }


    /**
     * 获取指定位置的周边配套
     */
    public RoomResult getAround(BaiduQueryAroundDTO dto) {

        ParameterizedTypeReference<BaiduApiResponse<List<BaiduAroundResultDTO>>> typeReference = new ParameterizedTypeReference<BaiduApiResponse<List<BaiduAroundResultDTO>>>() {
        };
        String url = "https://api.map.baidu.com/place/v2/search?query=" + dto.getQuery() +
            "&location=" + dto.getLat() + "," + dto.getLng() +
            "&radius=1000&output=" + OUT_PUT +
            "&ak=" + properties.getBaiduMap().getAk();
        BaiduApiResponse<List<BaiduAroundResultDTO>> apiResponse = doRequest(url, typeReference);
        if (!apiResponse.isSuccess()) {
            log.warn("data:{}", apiResponse.getMessage());
        }
        return RoomResult.success(apiResponse.getResults());
    }

//    坐标转换

}
